home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / setup / vbnet / 09 array, lists, and collections / collectionsdemo / module1.vb < prev   
Encoding:
Text File  |  2002-03-20  |  29.1 KB  |  805 lines

  1. Imports System.Globalization
  2. Imports System.IO
  3. Imports Microsoft.Win32
  4.  
  5. Module MainModule
  6.  
  7.     Sub Main()
  8.         ' Run one of the Textxxxx procedures below by uncommenting only one statement
  9.  
  10.         'TestArrays()
  11.         'TestArraysWithNonZeroLBound()
  12.         'TestArrayCopySort()
  13.         'TestArraySearches()
  14.         'TestJaggedArray()
  15.         'TestBitArray()
  16.         'TestStack()
  17.         'TestQueue()
  18.         'TestArrayList()
  19.         'TestHashtable()
  20.         'TestSortedList()
  21.         'TestCollectionPerformance()
  22.         'TestStringCollection()
  23.         'TestStringDictionary()
  24.         'TestReadOnlyCollectionBase()
  25.         'TestCollectionBase()
  26.         'TestDictionaryBase()
  27.  
  28.         ' These statements are usuful when running inside Visual Studio.NET
  29.         Console.WriteLine("")
  30.         Console.WriteLine(">>> Press Enter to terminate the program <<<")
  31.         Console.ReadLine()
  32.     End Sub
  33.  
  34.     ' this procedure tests arrays
  35.  
  36.     Sub TestArrays()
  37.         ' An array initialized with the powers of 2.
  38.         Dim intArr() As Integer = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}
  39.         ' Non-initialized 2-dimensional array 
  40.         Dim lngArr(10, 20) As Long
  41.         ' An empty array
  42.         Dim dblArr() As Double
  43.  
  44.         ' Create and initialize an array on the fly.
  45.         Dim ValueArray() As Long
  46.         ValueArray = New Long() {2, 3, 5, 9}
  47.  
  48.         ' test for an empty array
  49.         If dblArr Is Nothing Then
  50.             ReDim dblArr(100)
  51.         End If
  52.  
  53.         ' number of dimension
  54.         Console.WriteLine(lngArr.Rank)     ' => 2
  55.         ' lngArr has 11*21 elements.
  56.         Console.WriteLine(lngArr.Length)   ' => 231
  57.  
  58.         Console.WriteLine(lngArr.GetLength(0))       ' => 11
  59.         Console.WriteLine(lngArr.GetLowerBound(1))   ' => 0
  60.         Console.WriteLine(lngArr.GetUpperBound(1))   ' => 200
  61.     End Sub
  62.  
  63.     ' this procedure tests arrays with LBound other than zero
  64.  
  65.     Sub TestArraysWithNonZeroLBound()
  66.         ' Create a bi-dimensional array that is equivalent 
  67.         ' to the following VB6 declaration
  68.         '     Dim(1 To 5, -10 To 10) As Integer
  69.  
  70.         ' Prepare an auxiliary array with the length along each direction.
  71.         Dim lengths() As Integer = {5, 21}
  72.         ' Prepare an auxiliary array with the starting index along each direction.
  73.         Dim lbounds() As Integer = {1, -10}
  74.         ' create a generic Array object from CreateInstance shared method.
  75.         Dim arrObj As Array = Array.CreateInstance(GetType(Integer), lengths, lbounds)
  76.  
  77.         ' assign it to an array with the right rank
  78.         Dim arr(,) As Integer = CType(arrObj, Integer(,))
  79.  
  80.         ' Prove that it worked.
  81.         Console.WriteLine(arr.GetLowerBound(0))      ' => 1
  82.         Console.WriteLine(arr.GetUpperBound(0))      ' => 5
  83.         Console.WriteLine(arr.GetLowerBound(1))      ' => -10
  84.         Console.WriteLine(arr.GetUpperBound(1))      ' => 10
  85.  
  86.         ' assign an element and read it back.
  87.         arr(1, -1) = 1234
  88.         Console.WriteLine(arr(1, -1))                ' => 1234
  89.     End Sub
  90.  
  91.     ' this procedure tests array copying and sorting
  92.  
  93.     Sub TestArrayCopySort()
  94.         ' Create and initialize an array (10 elements).
  95.         Dim sourceArr() As Integer = {1, 2, 3, 5, 7, 11, 13, 17, 19, 23}
  96.         ' Create the destination array (must be same size or larger).
  97.         Dim destArr(20) As Integer
  98.         ' Copy the source array into the second half of the destination array.
  99.         sourceArr.CopyTo(destArr, 10)
  100.         ' prove that it worked - elements 10-19 are non-zero.
  101.         Dim i As Integer
  102.         For i = 0 To UBound(destArr)
  103.             Console.WriteLine(CStr(i) & " => " & destArr(i))
  104.         Next
  105.  
  106.         Dim targetArray(100) As Integer
  107.         Dim rand As New Random()
  108.         For i = 0 To 100
  109.             targetArray(i) = rand.Next(-1000, 1000)
  110.         Next
  111.         ' Sort only elements [10,100] of the targetArray.
  112.         ' Second argument is starting index, last argument is length of the subarray.
  113.         Array.Sort(targetArray, 10, 91)
  114.         ' display result
  115.         Console.Write("Elements 0-9 are unsorted: ")
  116.         For i = 0 To 9
  117.             Console.Write(CStr(targetArray(i)) & " ")
  118.         Next
  119.         Console.WriteLine("")
  120.         Console.Write("Elements 10-100 are sorted: ")
  121.         For i = 10 To 100
  122.             Console.Write(CStr(targetArray(i)) & " ")
  123.         Next
  124.         Console.WriteLine("")
  125.  
  126.         ' sort structures using a parallel key array
  127.  
  128.         ' Create a test array.
  129.         Dim employees() As Employee = { _
  130.             New Employee("Joe", "Doe", #3/1/2001#), _
  131.             New Employee("Robert", "Smith", #8/12/2000#), _
  132.             New Employee("Ann", "Douglas", #11/1/1999#)}
  133.  
  134.         ' Create a parallel array of hiring dates.
  135.         Dim hireDates(UBound(employees)) As Date
  136.         Dim j As Integer
  137.         For j = 0 To employees.Length - 1
  138.             hireDates(j) = employees(j).HireDate
  139.         Next
  140.         ' Sort the array of Employees using HireDates to provide the keys.
  141.         Array.Sort(hireDates, employees)
  142.         ' Prove that the array is sorted on the HireDate field.
  143.         For i = 0 To employees.Length - 1
  144.             Console.WriteLine(employees(i).Description)
  145.         Next
  146.         Console.WriteLine("")
  147.  
  148.         ' Add a fourth employee.
  149.         ReDim Preserve employees(3)
  150.         employees(3) = New Employee("Chris", "Doe", #5/9/2000#)
  151.         ' Extend the key array as well รป no need to re-initialize it.
  152.         ReDim Preserve hireDates(3)
  153.         hireDates(3) = employees(3).HireDate
  154.         ' Re-sort the new, larger array.
  155.         Array.Sort(hireDates, employees)
  156.         ' Prove that the array is sorted on the HireDate field.
  157.         For i = 0 To employees.Length - 1
  158.             Console.WriteLine(employees(i).Description)
  159.         Next
  160.         Console.WriteLine("")
  161.  
  162.         ' make both arrays larger.
  163.         ReDim Preserve employees(10)
  164.         ReDim Preserve hireDates(10)
  165.  
  166.         ' Sort only the portion actually used.
  167.         Array.Sort(hireDates, employees, 0, 4)
  168.         ' Prove that the array is sorted on the HireDate field.
  169.         For i = 0 To 10
  170.             Console.WriteLine(employees(i).Description)
  171.         Next
  172.  
  173.         ' copy a sub array
  174.         Dim intArr() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  175.         Dim intArr2(20) As Integer
  176.         ' Copy the entire source array into the first half of target array.
  177.         Array.Copy(intArr, intArr2, 10)
  178.         For i = 0 To UBound(intArr2)
  179.             Console.Write(CStr(intArr2(i)) & " ")     ' => 1 2 3 4 5 6 7 8 9 10 0 0 0 0 ...
  180.         Next
  181.         Console.WriteLine("")
  182.  
  183.         ' Copy elements at index 5-9 to the end of destArr.
  184.         Array.Copy(intArr, 5, intArr2, 15, 5)
  185.         ' This is the first element that has been copied.
  186.         Console.WriteLine(intArr2(15))               ' => 6
  187.  
  188.         ' This Copy operation succeeds even if array types are different.
  189.         Dim intArr3() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  190.         Dim lngArr3(20) As Long
  191.         Array.Copy(intArr3, lngArr3, 10)
  192.  
  193.         ' This Copy operation fails with TypeMismatchException.
  194.         '   (But you can carry it out with an explicit For loop.)
  195.         Dim lngArr4() As Long = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  196.         Dim intArr4(20) As Integer
  197.         ' Next statement throws a TypeMismatchException (narrowing conversion)
  198.         Try
  199.             Array.Copy(lngArr4, intArr4, 10)
  200.         Catch ex As Exception
  201.             Console.WriteLine(ex.Message)
  202.         End Try
  203.  
  204.         Dim lngArr5() As Long = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  205.         ' Delete element at index 4.
  206.         Array.Copy(lngArr5, 5, lngArr5, 4, 5)
  207.         ' Complete the delete operation by clearing the last element.
  208.         Array.Clear(lngArr5, lngArr5.GetUpperBound(0), 1)
  209.         ' Now the array contains: {1, 2, 3, 4, 6, 7, 8, 9, 10, 0}
  210.         For i = 0 To UBound(lngArr5)
  211.             Console.Write(CStr(lngArr5(i)) & " ")     ' => 1, 2, 3, 4, 6, 7, 8, 9, 10, 0
  212.         Next
  213.         Console.WriteLine("")
  214.         Console.WriteLine("")
  215.  
  216.         ' Show that arrays are stored in rowwise fashion.
  217.         Dim souArr(,) As Integer = {{1, 2, 3}, {4, 5, 6}}
  218.         Dim desArr(2, 1) As Integer
  219.         Array.Copy(souArr, desArr, 6)
  220.         For i = 0 To 2
  221.             For j = 0 To 1
  222.                 Console.WriteLine("desArr({0},{1}) = {2}", i, j, desArr(i, j))
  223.             Next
  224.         Next
  225.         Exit Sub
  226.     End Sub
  227.  
  228.     ' generic routine that deletes an element in any type of array.
  229.  
  230.     Sub ArrayDeleteElement(ByVal arr As Array, ByVal index As Integer)
  231.         ' Shift elements from arr(index+1) to arr(index).
  232.         Array.Copy(arr, index + 1, arr, index, UBound(arr) - index)
  233.         ' Clear the last element.
  234.         arr.Clear(arr, arr.GetUpperBound(0), 1)
  235.     End Sub
  236.  
  237.     ' A generic routine that inserts an element in any type of array.
  238.  
  239.     Sub ArrayInsertElement(ByVal arr As Array, ByVal index As Integer, Optional ByVal newValue As Object = Nothing)
  240.         ' shift elements from arr(index) to arr(index+1) to make room.
  241.         Array.Copy(arr, index, arr, index + 1, arr.Length - index - 1)
  242.         ' Assign the element using the SetValue method
  243.         arr.SetValue(newValue, index)
  244.     End Sub
  245.  
  246.     ' this procedure tests array searches
  247.  
  248.     Sub TestArraySearches()
  249.         Dim strArr() As String = {"Robert", "Joe", "Ann", "Chris", "Joe"}
  250.         ' search for the "Ann" value
  251.         Console.WriteLine(Array.IndexOf(strArr, "Ann"))   ' => 2
  252.         ' Note that string searches are case-sensitive.
  253.         Console.WriteLine(Array.IndexOf(strArr, "ANN"))   ' => -1
  254.  
  255.         ' searches for all the occurrences of the "Joe" string.
  256.         Dim index As Integer = -1
  257.         Do
  258.             ' Search next occurrence.
  259.             index = Array.IndexOf(strArr, "Joe", index + 1)
  260.             ' Exit the loop if not found.
  261.             If index = -1 Then Exit Do
  262.             Console.WriteLine("Found at index " & index.ToString)
  263.         Loop
  264.  
  265.         ' A revised version of the search loop, that searches
  266.         ' from higher indices towards the beginning of the array.
  267.         index = strArr.Length
  268.         Do
  269.             index = Array.LastIndexOf(strArr, "Joe", index - 1)
  270.             If index = -1 Then Exit Do
  271.             Console.WriteLine("Found at index " & index.ToString)
  272.         Loop
  273.  
  274.         ' Binary search on a sorted array
  275.         Dim strArr2() As String = {"Ann", "Chris", "Joe", "Robert", "Sam"}
  276.         Console.WriteLine(Array.BinarySearch(strArr2, "Chris"))  ' => 1
  277.  
  278.         ' an unsuccessful search
  279.         index = Array.BinarySearch(strArr2, "David")
  280.         If index >= 0 Then
  281.             Console.WriteLine("Found at index " & index.ToString)
  282.         Else
  283.             ' Negate the result to get the index for insertion point.
  284.             index = Not index
  285.             Console.WriteLine("Not Found. Insert at index " & index.ToString)
  286.             ' => Not found. Insert at index 2
  287.         End If
  288.  
  289.     End Sub
  290.  
  291.     ' this procedure tests arrays of arrays
  292.  
  293.     Sub TestJaggedArray()
  294.         ' Initialize an array of arrays.
  295.         Dim arr()() As String = {New String() {"a00"}, _
  296.             New String() {"a10", "a11"}, _
  297.             New String() {"a20", "a21", "a22"}, _
  298.             New String() {"a30", "a31", "a32", "a33"}}
  299.  
  300.         ' Show how you can reference an element.
  301.         Console.WriteLine(arr(3)(1))                    ' => a31
  302.  
  303.         ' Assign an entire row of elements.
  304.         arr(0) = New String() {"a00", "a01", "a02"}
  305.  
  306.         ' Read an element just added.
  307.         Console.WriteLine(arr(0)(2))                    ' => a02
  308.  
  309.         ' Expand one of the elements.
  310.         ReDim Preserve arr(1)(3)
  311.         ' Assign the new elements (now Nothing)
  312.         arr(1)(2) = "a12"
  313.         arr(1)(3) = "a13"
  314.         ' Read back one of them
  315.         Console.WriteLine(arr(1)(2))                    ' => a12
  316.     End Sub
  317.  
  318.     ' this procedure tests the BitArray class
  319.  
  320.     Sub TestBitArray()
  321.         ' Provide the number of elements (all initialized to False).
  322.         Dim ba As New BitArray(1024)
  323.         ' Provide the number of elements, and initialize then to a value.
  324.         Dim ba2 As New BitArray(1024, True)
  325.  
  326.         ' Initialize it from an array of Boolean, Byte, or Integer.
  327.         Dim boolArr(1023) As Boolean
  328.         ' ... (initialize the boolArr array)...
  329.         Dim ba3 As New BitArray(boolArr)
  330.  
  331.         ' Initialize it from another BitArray object.
  332.         Dim ba4 As New BitArray(ba)
  333.  
  334.         ' retrieve number of elements.
  335.         Console.WriteLine(ba.Count)                 ' => 1024
  336.         Console.WriteLine(ba.Length)                ' => 1024
  337.  
  338.         ' Set element at index 100 and read it back.
  339.         ba.Set(9, True)
  340.         Console.WriteLine(ba.Get(9))                ' => True
  341.  
  342.         ' Move all the elements back to an Integer array.
  343.         Dim intArr(31) As Integer
  344.         ' Second argument is the index where the copy begins in target array.
  345.         ba.CopyTo(intArr, 0)
  346.         Console.WriteLine(intArr(0))                ' => 512
  347.  
  348.         ' complements all the bits in ba
  349.         ba.Not()                         ' no arguments
  350.         ' AND all the bits in ba with the complement of all the bits in ba2.
  351.         ba.And(ba2.Not)
  352.         ' Set all the bits to True.
  353.         ba.SetAll(True)
  354.  
  355.         ' count how many 1's are in this BitArray
  356.         Dim b As Boolean
  357.         Dim TrueCount As Integer
  358.         For Each b In ba
  359.             If b Then TrueCount += 1
  360.         Next
  361.         Console.Write("Found " & TrueCount.ToString & " True values.")
  362.     End Sub
  363.  
  364.     ' this procedure tests the Stack class
  365.  
  366.     Sub TestStack()
  367.         ' Define a stack with initial capacity of 100 elements.
  368.         Dim st As New Stack(100)
  369.  
  370.         ' Push three values onto the stack.
  371.         st.Push(10)
  372.         st.Push(20)
  373.         st.Push(30)
  374.         ' Pop the value on top of the stack and display its value.
  375.         Console.WriteLine(st.Pop)       ' => 30
  376.         ' Read the value on top of the stack without popping it.
  377.         Console.WriteLine(st.Peek)      ' => 20
  378.         ' Now pop it.
  379.         Console.WriteLine(st.Pop)       ' => 20
  380.         ' Determine how many elements are now in the stack.
  381.         Console.WriteLine(st.Count)     ' => 1
  382.         Console.WriteLine(st.Pop)       ' => 10
  383.         ' Check that the stack is now empty.
  384.         Console.WriteLine(st.Count)     ' => 0
  385.  
  386.         st.Push(10)
  387.         ' Is the value 10 somewhere in the stack?
  388.         If st.Contains(10) Then Console.Write("Found")
  389.     End Sub
  390.  
  391.     ' this procedure tests the Queue object
  392.  
  393.     Sub TestQueue()
  394.         Dim qu As New Queue(100)
  395.         ' Insert three values in the queue.
  396.         qu.Enqueue(10)
  397.         qu.Enqueue(20)
  398.         qu.Enqueue(30)
  399.         ' Extract the first value and display it.
  400.         Console.WriteLine(qu.Dequeue)    ' => 10
  401.         ' Read the next value but don't extract it.
  402.         Console.WriteLine(qu.Peek)       ' => 20
  403.         ' Extract it.
  404.         Console.WriteLine(qu.Dequeue)    ' => 20
  405.         ' Check how many items are still in the queue.
  406.         Console.WriteLine(qu.Count)      ' => 1
  407.         ' Extract the last element and check that the queue is now empty.
  408.         Console.WriteLine(qu.Dequeue)    ' => 30
  409.         Console.WriteLine(qu.Count)      ' => 0
  410.     End Sub
  411.  
  412.     ' this procedure tests the ArrayList object
  413.  
  414.     Sub TestArrayList()
  415.         ' Create an ArrayList with initial capacity of 1000 elements.
  416.         Dim al As New ArrayList(1000)
  417.  
  418.         ' Create an ArrayList with 100 elements equal to a null string.
  419.         al = ArrayList.Repeat("", 100)
  420.  
  421.         ' Ensure you start with an empty ArrayList.
  422.         al.Clear()
  423.         ' Append the elements "Joe" and "Ann" at the end of the ArrayList.
  424.         al.Add("Joe")
  425.         al.Add("Ann")
  426.         ' Insert "Robert" item at the beginning of the list (Index is zero-based).
  427.         al.Insert(0, "Robert")
  428.         ' Remove "Joe" from the list.
  429.         al.Remove("Joe")
  430.         ' Remove the first element of the list ("Robert" in this case).
  431.         al.RemoveAt(0)
  432.  
  433.         ' two ways to remove all the elements equal to a given value
  434.  
  435.         ' Using the IndexOf method 
  436.         Do While al.IndexOf("element to remove") >= 0
  437.             al.Remove("element to remove")
  438.         Loop
  439.  
  440.         ' Same as previous one, but uses the Contains method.
  441.         Do While al.Contains("element to remove")
  442.             al.Remove("element to remove")
  443.         Loop
  444.  
  445.         ' test the ArrayListJoin function
  446.         Dim al2 As New ArrayList()
  447.         al2.Add("Frank")
  448.         al2.Add("Lee")
  449.         al2.Add("Nick")
  450.  
  451.         al = ArrayListJoin(al, al2)
  452.         Dim o As Object
  453.         For Each o In al
  454.             Console.Write(o)            ' => Ann Frank Lee Nick
  455.             Console.Write(" ")
  456.         Next
  457.         Console.WriteLine("")
  458.  
  459.         ' Insert all the items of AL2 at the beginning of current ArrayList.
  460.         al.InsertRange(0, al2)
  461.         For Each o In al
  462.             Console.Write(o)            ' => Frank Lee Nick Ann Frank Lee Nick
  463.             Console.Write(" ")
  464.         Next
  465.         Console.WriteLine("")
  466.  
  467.         ' Delete the last 4 elements (Assumes there are >= 4 elements).
  468.         al.RemoveRange(al.Count - 4, 4)
  469.         For Each o In al
  470.             Console.Write(o)            ' => Frank Lee Nick
  471.             Console.Write(" ")
  472.         Next
  473.         Console.WriteLine("")
  474.  
  475.         ' Extract elements to an Object array (never raises an error).
  476.         Dim objArr() As Object = al.ToArray()
  477.         ' Extract elements to a String array (might throw an InvalidCastException.)
  478.         ' (Requires CType if Option Strict is on.)
  479.         Dim strArr() As String = CType(al.ToArray(GetType(String)), String())
  480.         For Each o In strArr
  481.             Console.Write(o)            ' => Frank Lee Nick
  482.             Console.Write(" ")
  483.         Next
  484.         Console.WriteLine("")
  485.  
  486.         ' Same as above, but uses the CopyTo method.
  487.         ' (Note that the target array must be large enough.)
  488.         Dim strArr2(al.Count) As String
  489.         al.CopyTo(strArr2)
  490.  
  491.         ' Copy only items [1,2], starting at element 4 in the target array.
  492.         Dim strArr3() As String = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
  493.         ' Syntax is: sourceIndex, target, destIndex, count.
  494.         al.CopyTo(0, strArr3, 4, 2)
  495.         For Each o In strArr3
  496.             Console.Write(o)            ' => 0 1 2 3 Lee Nick 6 7 8 9 
  497.             Console.Write(" ")
  498.         Next
  499.         Console.WriteLine("")
  500.     End Sub
  501.  
  502.     ' a reusable function that merges two ArrayList objects
  503.  
  504.     Function ArrayListJoin(ByVal al1 As ArrayList, ByVal al2 As ArrayList) As ArrayList
  505.         ' Note how we avoid time-consuming reallocations.
  506.         ArrayListJoin = New ArrayList(al1.Count + al2.Count)
  507.         ' Append the items in the two ArrayList arguments.
  508.         ArrayListJoin.AddRange(al1)
  509.         ArrayListJoin.AddRange(al2)
  510.     End Function
  511.  
  512.     ' this procedure tests HashTable objects
  513.  
  514.     Sub TestHashtable()
  515.         ' Default load factor and initial capacity.
  516.         Dim ht As New Hashtable()
  517.         ' Default load factor and specified initial capacity.
  518.         Dim ht2 As New Hashtable(1000)
  519.         ' Specified initial capability and custom load factor.
  520.         Dim ht3 As New Hashtable(1000, 0.8)
  521.  
  522.         ' Decrease the load factor of the current Hashtable.
  523.         ht = New Hashtable(ht, 0.5)
  524.  
  525.         ' Syntax for Add method is .Add(key, value).
  526.         ht.Add("Joe", 12000)
  527.         ht.Add("Ann", 13000)
  528.         ' Referencing a new key creates an element.
  529.         ht.Item("Robert") = 15000
  530.         ' Item is the default member, so you can omit its name.
  531.         ht("Chris") = 11000
  532.         Console.Write(ht("Joe"))     ' => 12000
  533.         ' The Item property lets you overwrite an existing element.
  534.         ' (Note that you need CInt if Option Strict is off.
  535.         ht("Ann") = CInt(ht("Ann")) + 1000
  536.         ' Note that keys are compared in case-insensitive mode,
  537.         ' thus the following statement creates a *new* element.
  538.         ht("ann") = 15000
  539.         ' Reading a non-existing element doesn't create it.
  540.         Console.WriteLine(ht("Lee"))       ' Doesn't display anything.
  541.  
  542.         ' Remove an element given its key.
  543.         ht.Remove("Chris")
  544.         ' How many elements are now in the hashtable?
  545.         Console.WriteLine(ht.Count)        ' => 4
  546.  
  547.         ' Adding an element that exists already throws an exception.
  548.         Try
  549.             ht.Add("Joe", 11500)
  550.         Catch ex As ArgumentException
  551.             Console.WriteLine(ex.Message)
  552.         End Try
  553.  
  554.         ' display elements in the Hashtable
  555.         Dim de As DictionaryEntry
  556.         For Each de In ht
  557.             Console.WriteLine("ht('" & de.Key.ToString & "') = " & de.Value.ToString)
  558.         Next
  559.  
  560.         ' Display all the keys in the hashtable.
  561.         Dim o As Object
  562.         For Each o In ht.Keys         ' Use ht.Values for all the values.
  563.             Console.WriteLine(o)
  564.         Next
  565.  
  566.         ' create a case-sensitive Hashtable
  567.         Dim ciht As Hashtable = _
  568.             Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable()
  569.         Try
  570.             ' the second statement causes an exception.
  571.             ciht.Add("ann", 1)
  572.             ciht.Add("ANN", 2)
  573.         Catch ex As Exception
  574.             Console.WriteLine(ex.message)
  575.         End Try
  576.     End Sub
  577.  
  578.     ' this procedure tests a SortedList object
  579.  
  580.     Sub TestSortedList()
  581.         ' A SortedList with default capacity (16 entries).
  582.         Dim sl1 As New SortedList()
  583.         ' A SortedList with specified initial capacity.
  584.         Dim sl2 As New SortedList(1000)
  585.  
  586.         ' A SortedList initialized with all the elements in an IDictionary object.
  587.         Dim ht As New Hashtable()
  588.         ht.Add("Robert", 100)
  589.         ht.Add("Ann", 200)
  590.         ht.Add("JOE", 300)
  591.         ht.Add("joe", 400)
  592.         Dim sl3 As New SortedList(ht)
  593.         ' display the elements in the SortedList
  594.         Dim de As DictionaryEntry
  595.         For Each de In sl3
  596.             Console.WriteLine("sl3('" & de.Key.ToString & "') = " & de.Value.ToString)
  597.         Next
  598.         Console.WriteLine("")
  599.  
  600.         ' A SortedList that sorts elements through a custom IComparer.
  601.         Dim sl4 As New SortedList(New ReverseStringComparer())
  602.  
  603.         ' A SortedList that loads all the elements in a Hashtable and 
  604.         ' sorts them with a custom IComparer object.
  605.         Dim sl5 As New SortedList(ht, New ReverseStringComparer())
  606.         For Each de In sl5
  607.             Console.WriteLine("sl5('" & de.Key.ToString & "') = " & de.Value.ToString)
  608.         Next
  609.         Console.WriteLine("")
  610.  
  611.         ' create a case-insensitive sortedlist
  612.         Dim sl6 As SortedList = _
  613.             Specialized.CollectionsUtil.CreateCaseInsensitiveSortedList()
  614.         sl6.Add("ann", 100)
  615.         sl6.Add("BOB", 200)
  616.         For Each de In sl6
  617.             Console.WriteLine("sl5('" & de.Key.ToString & "') = " & de.Value.ToString)
  618.         Next
  619.         ' prove that you can't add two elements whose key differs only for its case.
  620.         Try
  621.             sl6.Add("bob", 200)
  622.         Catch ex As Exception
  623.             Console.WriteLine(ex.Message)
  624.         End Try
  625.     End Sub
  626.  
  627.     ' this procedure compares the performance of a few collection-like objects
  628.  
  629.     Sub TestCollectionPerformance()
  630.         Const numElements As Integer = 100000
  631.         Dim al As New ArrayList(numElements)
  632.         Dim startTime As Date
  633.         Dim i As Integer
  634.  
  635.         ' create an array of CStr(n) values, so that the CStr() function doesn't
  636.         ' affect benchmarks
  637.         Dim num(numElements) As String
  638.         For i = 0 To numElements
  639.             num(i) = CStr(i)
  640.         Next
  641.  
  642.         ' load strings into an ArrayList
  643.         startTime = Now
  644.         For i = 1 To numElements
  645.             al.Add(num(i))
  646.         Next
  647.         Console.WriteLine("ArrayList: " & Now.Subtract(startTime).ToString & " secs.")
  648.         ' clear memory before running another benchmark
  649.         al = Nothing
  650.         GC.Collect()
  651.  
  652.         ' load strings into a HashTable
  653.         Dim ht As New Hashtable(numElements)
  654.         startTime = Now
  655.         For i = 1 To numElements
  656.             ht.Add(num(i), num(i))
  657.         Next
  658.         Console.WriteLine("HashTable: " & Now.Subtract(startTime).ToString & " secs.")
  659.         ' clear memory before running another benchmark
  660.         al = Nothing
  661.         GC.Collect()
  662.  
  663.         ' load strings into a SortedList
  664.         Dim sl As New SortedList(numElements)
  665.         startTime = Now
  666.         For i = 1 To numElements
  667.             sl.Add(num(i), num(i))
  668.         Next
  669.         Console.WriteLine("SortedList: " & Now.Subtract(startTime).ToString & " secs.")
  670.         ' clear memory before running another benchmark
  671.         al = Nothing
  672.         GC.Collect()
  673.  
  674.         ' load strings into a StringCollection
  675.         Dim sc As New Specialized.StringCollection()
  676.         startTime = Now
  677.         For i = 1 To numElements
  678.             sc.Add(num(i))
  679.         Next
  680.         Console.WriteLine("StringCollection: " & Now.Subtract(startTime).ToString & " secs.")
  681.         ' clear memory before running another benchmark
  682.         al = Nothing
  683.         GC.Collect()
  684.  
  685.         ' load strings into a StringDictionary
  686.         Dim sd As New Specialized.StringDictionary()
  687.         startTime = Now
  688.         For i = 1 To numElements
  689.             sd.Add(num(i), num(i))
  690.         Next
  691.         Console.WriteLine("StringDictionary: " & Now.Subtract(startTime).ToString & " secs.")
  692.         ' clear memory before running another benchmark
  693.         al = Nothing
  694.         GC.Collect()
  695.     End Sub
  696.  
  697.     ' this procedure tests a StringCollection object
  698.  
  699.     Sub TestStringCollection()
  700.         ' Create a StringCollection (no support for initial capability).
  701.         Dim sc As New System.Collections.Specialized.StringCollection()
  702.  
  703.         ' Fill it with month names in current language, in one operation.
  704.         ' (We leverage the DateFormatInfo object's MonthNames method, which
  705.         '  returns an array of strings, which in turn implements IList interface.)
  706.         sc.AddRange(DateTimeFormatInfo.CurrentInfo.MonthNames())
  707.  
  708.         ' Display the StringCollection contents.
  709.         Dim s As String
  710.         For Each s In sc
  711.             Console.Write(s & " ")
  712.         Next
  713.         Console.WriteLine("")
  714.  
  715.         ' A temporary ArrayList that wraps around the StringCollection object.
  716.         Dim al As ArrayList = ArrayList.Adapter(sc)
  717.         ' Sort the inner StringCollection in reverse order through the wrapper.
  718.         al.Sort()
  719.         al.Reverse()
  720.         ' Destroy the wrapper object, which isn't necessary any longer.
  721.         al = Nothing
  722.  
  723.         ' Display the StringCollection contents.
  724.         For Each s In sc
  725.             Console.Write(s & " ")
  726.         Next
  727.         Console.WriteLine("")
  728.     End Sub
  729.  
  730.     ' this procedure tests the StringDictionary object
  731.  
  732.     Sub TestStringDictionary()
  733.         Dim sd As New System.Collections.Specialized.StringDictionary()
  734.         sd.Add("Ann", "Marketing")
  735.         sd.Add("Joe", "Sales")
  736.         sd.Add("Robert", "Administration")
  737.  
  738.         Dim de As DictionaryEntry
  739.         For Each de In sd
  740.             Console.WriteLine(de.Key.ToString & " = " & de.Value.ToString)
  741.         Next
  742.         Console.WriteLine("")
  743.  
  744.         Dim nvc As New System.Collections.Specialized.NameValueCollection()
  745.         nvc.Add("Ann", "Marketing")
  746.         nvc.Add("Ann", "Sales")
  747.         ' get all the strings
  748.         Dim s As String
  749.         For Each s In nvc.AllKeys
  750.             Console.WriteLine(s & " = " & nvc(s))
  751.         Next
  752.     End Sub
  753.  
  754.     ' this procedure tests the ReadOnlyCollectionBase abstract class
  755.  
  756.     Sub TestReadOnlyCollectionBase()
  757.         ' Display powers of 2 up to 2^20.
  758.         Dim powers As New PowersOfTwoCollection(20)
  759.         ' The Count property is provided by the base class.
  760.         Console.WriteLine(powers.Count)     ' => 21
  761.  
  762.         ' The For Each support is also provided by the base class.
  763.         Dim n As Long
  764.         For Each n In powers
  765.             Console.WriteLine(n)
  766.         Next
  767.  
  768.         ' Assign the value of 2^15 to a variable. 
  769.         ' Note that no casting is required, because the collection is strong-typed.
  770.         Dim lngValue As Long = powers(15)
  771.     End Sub
  772.  
  773.     ' this procedure tests the CollectionBase class
  774.  
  775.     Sub TestCollectionBase()
  776.         Dim squares As New SquareCollection()
  777.         squares.Add(New Square(10))
  778.         squares.Add(New Square(20))
  779.         squares.Add(New Square(30))
  780.         squares.Create(40)
  781.         squares.Create(50)
  782.  
  783.         ' The RemoveAt method is provided by the base class.
  784.         squares.RemoveAt(0)
  785.  
  786.         Dim sq As Square
  787.         For Each sq In squares
  788.             Console.WriteLine(sq.Side)                  ' => 20 30 40 50
  789.         Next
  790.         Console.WriteLine("Total area = " & squares.TotalArea.ToString)
  791.     End Sub
  792.  
  793.     ' this procedure tests the DictionaryBase class
  794.  
  795.     Sub TestDictionaryBase()
  796.         Dim sq As New SquareDictionary()
  797.         sq.Create("First", 10)
  798.         sq.Create("Second", 20)
  799.         sq.Create("Third", 30)
  800.  
  801.         Console.WriteLine(sq("Second").Side)    ' => 20
  802.     End Sub
  803.  
  804. End Module
  805.